<?php

namespace services\common;

use Yii;
use common\models\patient\PatientActiveRecord;
use common\models\patient\User;
use common\components\Service;
use yii\web\HttpException;

class ActiveLogService extends Service
{
    /**
     * 患者活跃时间存储
     *
     * @param int $patient_user_id
     * @param string $remark
     * @param int $memberId
     * @return bool
     * @throws HttpException
     * @author chenyuebin
     */
    public static function activeLog(int $patient_user_id, string $remark, int $memberId)
    {
        if ($patient_user_id == 0) {
            return true;
        }
        // 预组装参数
        $active_time = date("Y-m-d H:i:s");
        $activeRecord = [
            'patient_user_id' => $patient_user_id,
            'patient_active_time' => $active_time,
            'remark' => $remark
        ];
        try {
            // redis暂存
            $redis = Yii::$app->redis;
            if ($val = $redis->get($patient_user_id)) {
                $arr = json_decode($val, true);
                $arr['active_time']['time'] = strtotime($active_time);
                $arr['active_time']['id'] = $patient_user_id;
                $arr['active_time']['belong_member_id'] = $memberId;
                array_push($arr['active_record'], $activeRecord);
                $data = json_encode($arr);
            } else {
                $redisData = [
                    'active_time' => [
                        'id' => $patient_user_id,
                        'belong_member_id' => $memberId,
                        'time' => strtotime($active_time),
                    ],
                    'active_record' => [$activeRecord]
                ];
                $data = json_encode($redisData);
            }
            $ret = $redis->set('active_time_' . $patient_user_id, $data);
        } catch (\Exception $exception) {
            throw new HttpException(500, $exception->getMessage());
        }

        return $ret;
    }

    /**
     * 定时执行患者活跃时间redis数据入库
     *
     * @return bool
     * @author chenyuebin
     */
    public static function saveActiveRecord()
    {
        $redis = Yii::$app->redis;
        $key = $redis->keys('active_time_*');
        foreach ($key as $value) {
            $newString = strstr($value, 'active_time_');
            $length = strlen('active_time_');
            $thisId = substr($newString, $length);
            if (User::find()->where(['id' => $thisId])->exists()) {
                $val = $redis->get($value);
                $arr = json_decode($val, true);

                $transaction = Yii::$app->db->beginTransaction();
                try {
                    User::updateAll(['active_time' => $arr['active_time']['time']], ['id' => $arr['active_time']['id'], 'belong_member_id' => $arr['active_time']['belong_member_id']]);
                    Yii::$app->db->createCommand()->batchInsert(PatientActiveRecord::tableName(), ['patient_user_id', 'patient_active_time', 'remark'], $arr['active_record'])->execute();
                    $redis->del($value);
                    $transaction->commit();
                } catch (\Exception $exception) {
                    $transaction->rollBack();
                    return false;
                }
                return true;
            }
        }
    }
}
